package com.elcl.storage;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

import com.elcl.andbaselibrary.R;
import com.elcl.util.ResourceUtils;

/**
 * @author LCL
 * 2014-12-17
 * SharedPreferences的存取
 */
public class SharedPreferencesUtils {
	public static SharedPreferences sharedPreferences;

	public static boolean setMemorySP(String key, Object value) {
		boolean result = false;
		getSharedPreference();
		Editor editor = sharedPreferences.edit();
		try {
			if (null != key) {
				if (null != value) {
					if (value instanceof Boolean) {
						editor.putBoolean(key, (Boolean) value);
					} else if (value instanceof Float) {
						editor.putFloat(key, (Float) value);
					} else if (value instanceof Integer) {
						editor.putInt(key, (Integer)value);
					} else if (value instanceof Long) {
						editor.putLong(key, (Long) value);
					} else if (value instanceof String) {
						editor.putString(key, (String) value);
					}else{
						return result;
					}
				}else{
					editor.remove(key);//如果内容为空值的话
					result = true;
				}
				editor.commit();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	@SuppressWarnings("unchecked")
	public static <T> T getMemorySP(String key, Object defaultValue,Class<T> type){
		Object result = null; 
		getSharedPreference();
		if (null != key) {
			if (Boolean.class.equals(type)) {
				result = sharedPreferences.getBoolean(key, (Boolean)defaultValue);
			}else if (String.class.equals(type)) {
				result = sharedPreferences.getString(key, (String)defaultValue);
			}else if (Float.class.equals(type)) {
				result = sharedPreferences.getFloat(key, (Float)defaultValue);
			}else if (Integer.class.equals(type)) {
				result = sharedPreferences.getInt(key, (Integer)defaultValue);
			}else if (Long.class.equals(type)) {
				result = sharedPreferences.getLong(key, (Long)defaultValue);
			}else{
				throw new RuntimeException(ResourceUtils.getString(R.string.sp_type_only));
			}
			if (null != result) {
			 	return (T)result;
			}
		}
		return null;
	}

	public static SharedPreferences getSharedPreference() {
		if (null == sharedPreferences) {
			sharedPreferences = PreferenceManager
					.getDefaultSharedPreferences(ApplicationCache.context);
		}
		return sharedPreferences;
	}
	
	
	
	/**
	 * 删除一个SharePreference中的值
	 * 
	 * @param key
	 * @return void
	 */
	public static void deleteSharePreferenceValue(String key) {
		getSharedPreference();
		Editor editor = sharedPreferences.edit();
		editor.remove(key);
		editor.commit();
	}
}
